<template>
  <div v-if="item.visible === '0'" class="menu-wrapper">
    <template v-for="item in menuData">

      <el-menu-item :key="resolvePath(item.path)" :index="resolvePath(item.path)" :class="{'submenu-title-noDropdown':!isNest}">
        <app-link v-if="item.meta" :to="resolvePath(item.path)">
          <item v-if="item.meta" :icon="item.meta && item.meta.icon" :title="item.meta.title" />
        </app-link>
      </el-menu-item>

      <el-submenu v-if="getChildrenLength()" ref="subMenu" :key="resolvePath(item.path)" :index="resolvePath(item.path)" popper-append-to-body popper-class="active-menu">
        <template slot="title">
          <item v-if="item.meta" :icon="item.meta && item.meta.icon" :title="item.meta.title" />
        </template>
        <sidebar-item
          v-for="child in item.children"
          :key="child.path"
          :is-nest="true"
          :item="child"
          :base-path="resolvePath(item.path)"
          class="nest-menu"
        />
      </el-submenu>
    </template>
  </div>
</template>

<script>
import path from 'path'
import { isExternal } from '@/utils/validate'
import Item from './Item'
import AppLink from './Link'
export default {
  name: 'SidebarItem',
  components: { Item, AppLink },
  props: {
    // route object
    menuData: {
      type: Array,
      default() {
        return []
      }
    },
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  data() {
    this.onlyOneChild = null
    return {}
  },
  methods: {
    getChildrenLength() {
      if (this.item.children && this.item.children.length > 0) {
        return true
      } else {
        return false
      }
    },
    hasOneShowingChild(children = [], parent) {
      if (children && children.length > 0) {
        const showingChildren = children.filter(item => {
          if (item.visible === '1') {
            return false
          } else {
            // Temp set(will be used if only has one showing child)
            this.onlyOneChild = item
            return true
          }
        })
        // When there is only one child router, the child router is displayed by default
        if (showingChildren.length === 1) {
          return true
        }
        // Show parent if there are no child router to display
        if (showingChildren.length === 0) {
          this.onlyOneChild = { ... parent, path: '', noShowingChildren: true }
          return true
        }
      }
      return false
    },
    resolvePath(routePath) {
      if (isExternal(routePath)) {
        return routePath
      }
      if (isExternal(this.basePath)) {
        return this.basePath
      }
      return path.resolve(this.basePath, routePath)
    }
  }
}
</script>
